﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using ClassLibraryDatabase;

namespace ClassLibraryBaseClass
{
	/// <summary>
	///Theater 的摘要说明
	/// </summary>
	public class Theater
	{
		private static readonly string _connectionString = DataBaseClass.GetConnectionString();
		private static string[] m_sTheaterInfoName = {"ID", "Name", "Address", "TelNumber"
                                                 , "Link", "Grade", "Intro"};
		/// <summary>
		/// 电影院编号ID属性及get方法
		/// </summary>
		private int _ID;
		public int ID
		{
			get { return _ID; }
		}
		/// <summary>
		/// 电影院名字Name属性及get方法
		/// </summary>
		private string _Name;
		public string Name
		{
			get { return _Name; }
		}
		/// <summary>
		/// 电影院地址Address属性及get方法
		/// </summary>
		private string _Address;
		public string Address
		{
			get { return _Address; }
			set { _Address = value; }
		}
		/// <summary>
		/// 电影院电话TelNumber属性及get/set方法
		/// </summary>
		private string _TelNumber;
		public string TelNumber
		{
			get { return _TelNumber; }
			set { _TelNumber = value; }
		}

		/// <summary>
		/// 电影院网站链接Link属性及get方法
		/// </summary>
		private string _Link;
		public string Link
		{
			get { return _Link; }
			set { _Link = value; }
		}
		/// <summary>
		/// 电影院评分Grade属性及其get/set方法
		/// </summary>
		private decimal _Grade;
		public decimal Grade
		{
			get { return _Grade; }
			set { _Grade = value; }
		}

		private string _Intro;
		public string Intro
		{
			get { return _Intro; }
			set { _Intro = value; }
		}

		private int _Count;
		public int Count
		{
			get { return _Count; }
			set { _Count = value; }
		}

		public Theater(int id, string name, string address, string telnumber
			, string link, decimal grade, string intro, int count)
		{
			_ID = id;
			_Name = name;
			_Address = address;
			_TelNumber = telnumber;
			_Link = link;
			_Grade = grade;
			_Intro = intro;
			_Count = count;
		}

		/// <summary>
		/// 添加一条电影院信息到数据库
		/// </summary>
		/// <param name="id">添加的电影院编号</param>
		/// <param name="name">添加的电影院名字</param>
		/// <param name="address">添加的电影院地址</param>
		/// <param name="telnumber">添加的电影院电话</param>
		/// <param name="link">添加的电影院网站链接</param>
		/// <param name="grade">添加的电影院评分</param>
		/// <returns>添加是否成功</returns>
		public static bool AddTheaterInfo(int id, string name, string address,
			string telnumber, string link, decimal grade, string intro, int count)
		{
			Theater theater = new Theater(id, name, address, telnumber
				, link, grade, intro, count);
			return theater.AddSelfInfo();
		}

		/// <summary>
		/// 将自身的信息添加到数据库中
		/// </summary>
		/// <returns>插入是否成功</returns>
		public bool AddSelfInfo()
		{
			int nT = 0;

			if (this.TelNumber != null)
				++nT;
			if (this.Link != null)
				++nT;
			if (this.Intro != null)
				++nT;

			nT += 4;
			string[] name = new string[nT];
			object[] value = new object[nT];

			//DataTable table = DataBaseClass.selectData(



			name[0] = "Name";
			value[0] = this.Name;

			name[1] = "Address";
			value[1] = this.Address;

			name[2] = "Count";
			value[2] = this.Count;



			int count = 3;
			if (this.TelNumber != null && this.TelNumber != "")
			{
				name[count] = "TelNumber";
				value[count] = this.TelNumber;
				count++;
			}

			if (this.Link != null && this.Link != "")
			{
				name[count] = "Link";
				value[count] = this.Link;
				count++;
			}

			if (this.Intro != null && this.Intro != "")
			{
				name[count] = "Intro";
				value[count] = this.Intro;
				count++;
			}
			name[count] = "Grade";
			value[count] = this.Grade;
			try
			{
				bool bT = DataBaseClass.insertData(name, value, "Theater", _connectionString);
				_ID = DataBaseClass.GetMaxID("Theater", _connectionString);
				return bT;
			}
			catch (SqlException e)
			{
				System.Console.Write("Theater类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (ArgumentException e)
			{
				System.Console.Write("Theater类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (InvalidOperationException e)
			{
				System.Console.Write("Theater类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (Exception e)
			{
				System.Console.Write("Theater类：");
				System.Console.WriteLine("未知错误:" + e.Message);
				return false;
			}
		}
		/// <summary>
		/// 根据电影院编号从数据库中获得一个电影院对象
		/// </summary>
		/// <param name="id">传入的电影院编号</param>
		/// <returns>Theater对象</returns>
		public static Theater GetTheaterByID(int id)
		{
			DataTable info = DataBaseClass.selectData("SELECT Name,Address,TelNumber,Link,Grade,Intro,Count"
				+ " FROM Theater WHERE ID = " + id, _connectionString);
			if (info.Rows.Count == 0)
				return null;
			Theater theater = new Theater(id, info.Rows[0]["Name"] as string
				, info.Rows[0]["Address"] as string, info.Rows[0]["TelNumber"] as string
				, info.Rows[0]["Link"] as string, (decimal)info.Rows[0]["Grade"]
				, info.Rows[0]["Intro"] as string, (int)info.Rows[0]["Count"]);

			return theater;
		}

		/// <summary>
		/// 根据电影院名从数据库中获得一个电影院对象
		/// </summary>
		/// <param name="name">传入的电影院名字字段</param>
		/// <returns>Theater对象</returns>
		public static Theater GetTheaterByName(string name)
		{
			DataTable info = DataBaseClass.selectData("SELECT ID,Address,TelNumber,Link,Grade,Intro,Count"
				+ " FROM Theater WHERE Name = \'" + name + "\'", _connectionString);
			if (info.Rows.Count == 0)
				return null;
			Theater theater = new Theater((int)info.Rows[0]["ID"], name, info.Rows[0]["Address"] as string
				, info.Rows[0]["Link"] as string, info.Rows[0]["TelNumber"] as string
				, (decimal)info.Rows[0]["Grade"], info.Rows[0]["Intro"] as string
				, (int)info.Rows[0]["Count"]);

			return theater;
		}

		/// <summary>
		/// 根据地区region限制条件从数据库中筛选出电影院列表
		/// </summary>
		/// <param name="region">地区限制条件</param>
		/// <returns>电影院对象Theater列表List</returns>
		public List<Theater> SiftTheaterListByRegion(string region)
		{
			//List<Theater> ls = new List<Theater>();
			DataTable info = DataBaseClass.selectData("SELECT * FROM Theater WHERE " +
				"Address Like \'%" + region + "%\'", _connectionString);

			return GetListFromDataTable(info);

		}

		public static DataTable SiftTheaterTableByRegion(string region)
		{
			//DataTable info = DataBaseClass.selectData("SELECT * FROM Theater WHERE CHARINDEX(\'" + region + "\',Address) > 0", _connectionString);
			DataTable info = DataBaseClass.selectData("SELECT * FROM Theater WHERE " +
				"Address Like \'%" + region + "%\'", _connectionString);
			return info;
		}
		/// <summary>
		/// 根据评分Grade限制条件从数据库中筛选出电影院列表
		/// </summary>
		/// <param name="condition">评分Grade限制条件</param>
		/// <returns>电影院对象Theater列表List</returns>
		public List<Theater> SiftTheaterListByGrade(string condition)
		{
			//   List<Theater> ls = new List<Theater>();
			DataTable info = DataBaseClass.selectData(m_sTheaterInfoName, condition
				, "Theater", _connectionString);
			//for (int i = 0; i < info.Rows.Count; i++)
			//{
			//    Theater theater = new Theater((int)info.Rows[i]["ID"], info.Rows[i]["Name"] as string
			//        , info.Rows[i]["Address"] as string, info.Rows[i]["Link"] as string
			//        , info.Rows[i]["TelNumber"] as string, (decimal)info.Rows[i]["Grade"]
			//        , info.Rows[i]["Intro"] as string);
			//    ls.Add(theater);
			//}
			return GetListFromDataTable(info);

			//return ls;
		}

		public static DataTable SiftTheaterTableByGrade(string condition)
		{
			DataTable info = DataBaseClass.selectData(m_sTheaterInfoName, condition
				, "Theater", _connectionString);
			return info;
		}

		/// <summary>
		/// 根据此电影院的信息获得目前此电影院上映电影的电影列表List
		/// </summary>
		/// <returns>Movie对象列表List</returns>
		public List<Movie> GetMovieListInTheater()
		{
			List<Movie> ls = new List<Movie>();
			DataTable info = DataBaseClass.selectData("SELECT * FROM Movies WHERE ID IN"
				+ " (SELECT DISTINCT MovieID FROM Session WHERE TheaterID=" + this.ID.ToString()
				+ ")", _connectionString);

			for (int i = 0; i < info.Rows.Count; i++)
			{
				Movie movie = new Movie((int)info.Rows[i]["ID"], info.Rows[i]["Name"] as string
					, info.Rows[i]["Director"] as string, info.Rows[i]["Actors"] as string
					, info.Rows[i]["Release"] as string, (int)info.Rows[i]["Length"]
					, info.Rows[i]["Language"] as string, info.Rows[i]["Type"] as string
					, info.Rows[i]["NTSC"] as string, (decimal)info.Rows[i]["Grade"]
					, info.Rows[i]["Image"] as string, info.Rows[i]["Intro"] as string);
				ls.Add(movie);
			}
			return ls;
		}

		/// <summary>
		/// 根据此电影院的信息获得目前此电影院上映电影的电影列表DataTable
		/// </summary>
		/// <returns>Movie对象数据表DataTable</returns>
		public DataTable GetMovieTableInTheater()
		{
			return DataBaseClass.selectData("SELECT * FROM Movies WHERE ID IN"
				+ " (SELECT DISTINCT MovieID FROM Session WHERE TheaterID=" + this.ID.ToString()
				+ ")", _connectionString);
		}

		/// <summary>
		/// 获得此电影院的评论列表List
		/// </summary>
		/// <returns>TCommentClass对象列表List</returns>
		public List<TComment> GetCommentsList()
		{
			List<TComment> ls;
			string[] tCommentInfoName = { "ID", "UserID", "TheaterID", "Date", "Title", "Detail" };
			DataTable info = DataBaseClass.selectData(tCommentInfoName, "TheaterID=" + this.ID.ToString()
				, "T_Comment", _connectionString);

			ls = TComment.GetListFromDataTable(info);
			return ls;
		}
		/// <summary>
		/// 获得此电影院的评论列表DataTable
		/// </summary>
		/// <returns>TCommentClass对象列表DataTable</returns>
		public DataTable GetCommentsTable()
		{
			string[] tCommentInfoName = { "ID", "UserID", "TheaterID", "Date", "Title", "Detail" };
			DataTable info = DataBaseClass.selectData(tCommentInfoName, "TheaterID=" + this.ID.ToString()
				, "T_Comment", _connectionString);
			return info;
		}
		/// <summary>
		/// 修改改电影院的评分，并保存
		/// </summary>
		/// <param name="id">电影院编号属性</param>
		/// <param name="newGrade">新评分</param>
		/// <returns>修改是否成功</returns>
		public bool ModifyTheaterGrade(decimal newGrade)
		{
			return DataBaseClass.Update("UPDATE Theater SET Grade = \'" + newGrade
				+ "\' WHERE ID = " + this.ID, _connectionString);
		}
		// <summary>
		/// 将自己的信息从数据库中删除
		/// </summary>
		/// <returns></returns>
		public bool[] DeleteSelfInfo()
		{
			return DeleteItemFromDatabase(this.ID);

		}
		/// <summary>
		/// 删除与此电影信息相关的所有信息，在"Session"和"T_Comment"中
		/// </summary>
		/// <param name="nID"></param>
		/// <returns></returns>
		public static bool[] DeleteItemFromDatabase(int nID)
		{
			bool[] bT = new bool[3];
			bool[] bF = DeleteRelationship(nID);
			bT[1] = false;
			bT[2] = false;
			bT[0] = DataBaseClass.deleteData("ID", nID, "Theater", _connectionString);
			return bT;
		}
		/// <summary>
		/// 删除与此电影信息相关的所有信息，在"Session"和"T_Comment"中
		/// </summary>
		/// <param name="nID"></param>
		/// <returns></returns>
		public static bool[] DeleteRelationship(int nID)
		{
			bool[] bT = { false, false };
			try
			{
				List<SessionInfo> list = SessionInfo.GetListByDataTable(DataBaseClass.selectData("SELECT * FROM Session WHERE TheaterID=" + nID, _connectionString));
				foreach (SessionInfo info in list)
				{
					info.DeleteSelfInfo();
				}
				bT[0] = true;
			}
			catch (Exception e)
			{
				bT[0] = false;
			}
			try
			{
				List<TComment> tList = TComment.GetListFromDataTable(DataBaseClass.selectData("SELECT * FROM T_Comment WHERE TheaterID=" + nID, _connectionString));
				foreach (TComment comment in tList)
				{
					comment.DelT_Comment();
				}
				bT[1] = true;
			}
			catch (Exception e)
			{
				bT[1] = false;
			}
			return bT;
		}
		/// <summary>
		/// 更新自身信息
		/// </summary>
		/// <param name="id">自身编号</param>
		/// <param name="name">自身名字</param>
		/// <param name="address">更新地址</param>
		/// <param name="telnumber">更新电话</param>
		/// <param name="link">更新网站链接</param>
		/// <param name="grade">更新评分</param>
		/// <param name="intro">更新介绍</param>
		/// <returns>更新是否成功</returns>
		public bool UpdateSelfInfo()
		{
			//string[] theaterInfoName = {"ID", "Name", "Address", "TelNumber", 
			//                               "Link", "Grade", "Intro", "Count"};
			//string[] theaterInfo = { this.ID.ToString(), this.Name, address
			//                           , telnumber, link, grade.ToString()
			//                           , intro, count.ToString() };
			//return DataBaseClass.Update(theaterInfoName, theaterInfo, "Theater", _connectionString);
			Theater theater = Theater.GetTheaterByID(this.ID);
			string sql = "UPDATE Movies SET ";
			if (this.Name != theater.Name)
				sql += " Name=" + this.Name + ",";
			if (this.Address != theater.Address)
				sql += "Address=" + this.Address + ",";
			if (this.TelNumber != theater.TelNumber)
				sql += "TelNumber=" + this.TelNumber + ",";
			if (this.Link != theater.Link)
				sql += "Link=" + this.Link + ",";
			if (this.Grade != theater.Grade)
				sql += "Grade=" + this.Grade.ToString() + ",";
			if (this.Intro != null && this.Intro != theater.Intro)
				sql += "Intro=" + this.Intro + ",";
			if (this.Count != theater.Count)
				sql += "Count=" + this.Count + ",";
			if (sql.EndsWith(","))
				sql.Remove(sql.Length - 1, 1);
			else if (sql.EndsWith("SET "))
				sql.Remove(sql.Length - 4, 4);
			sql += " WHERE ID=" + this.ID.ToString();
			return DataBaseClass.Update(sql, _connectionString);
		}
		/// <summary>
		/// 根据ID从数据库获得电影院信息对象
		/// </summary>
		/// <param name="id">传入电影院ID</param>
		/// <returns>电影院信息对象Theater</returns>
		//public static Theater GetTheaterByID(int id)
		//{
		//    DataTable info = DataBaseClass.selectData("SELECT ID FROM Theater WHERE ID = "
		//        + id, _connectionString);
		//    Theater theater = new Theater(id, (string)info.Rows[0]["Name"], (string)info.Rows[0]["Address"]
		//        , (string)info.Rows[0]["Link"], (string)info.Rows[0]["TelNumber"]
		//        , (int)info.Rows[0]["Grade"]);

		//    return theater;
		//}

		/// <summary>
		/// 将DataTable对象转换为数据列表List
		/// </summary>
		/// <param name="dt">DataTable对象</param>
		/// <returns>数据列表List</returns>
		public List<Theater> GetListFromDataTable(DataTable dt)
		{
			List<Theater> temp = new List<Theater>();
			for (int i = 0; i < dt.Rows.Count; i++)
			{
				Theater theater = new Theater((int)dt.Rows[i]["ID"], dt.Rows[i]["Name"] as string
					, dt.Rows[i]["Address"] as string, dt.Rows[i]["Link"] as string
					, dt.Rows[i]["TelNumber"] as string, (decimal)dt.Rows[i]["Grade"]
					, dt.Rows[i]["Intro"] as string, (int)dt.Rows[i]["Count"]);
				temp.Add(theater);
			}
			return temp;
		}
		public bool GetGrade(decimal dT)
		{
			try
			{
				this.Grade = (this.Grade * this.Count + dT) / (++_Count);
				return DataBaseClass.Update("UPDATE Theater SET Grade=" + this.Grade + ", Count=" + _Count + " WHERE ID=" + this.ID, _connectionString);
			}
			catch (SqlException e)
			{
				System.Console.Write("Theater类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (ArgumentException e)
			{
				System.Console.Write("Theater类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (InvalidOperationException e)
			{
				System.Console.Write("Theater类：");
				System.Console.WriteLine(e.Message);
				return false;
			}
			catch (Exception e)
			{
				System.Console.Write("Theater类：");
				System.Console.WriteLine("未知错误:" + e.Message);
				return false;
			}
		}
		static public int GetMaxID()
		{
			DataTable table = DataBaseClass.selectData("SELECT MAX(ID) AS ID FROM Theater", _connectionString);
			return Convert.ToInt32(table.Rows[0]["ID"]);
		}
		/// <summary>
		/// 获取指定含pageSize个信息的数据表
		/// </summary>
		/// <param name="pageIndex">页面索引</param>
		/// <param name="pageSize">页面大小</param>
		/// <returns>含pageSize个信息的数据表对象</returns>
		public static DataTable GetPatialTheaterTable(int pageIndex, int pageSize)
		{
			int firstPage = pageIndex * pageSize;
			DataTable info = DataBaseClass.selectPatialData("SELECT * FROM Theater ORDER BY Grade DESC"
				, firstPage, pageSize, _connectionString);
			return info;
		}
	}
	public class Test1
	{
		public static void Test()
		{
			Theater d = Theater.GetTheaterByName("DSF");

			if (d != null)
				d.DeleteSelfInfo();
			d = Theater.GetTheaterByName("DSF1asdf212");
			if (d != null)
				d.DeleteSelfInfo();
			Theater.AddTheaterInfo(-1, "DSF", "ASDFASFasdf", "123afsd15", "5465adf43.com", 5.0M, "ASasdfDF", 12);
			Theater t = new Theater(-1, "DSF1asdf212", "ASDFasdfASF", "12fsd315", "546asf543.com", 5.0M, "AasdfSDF", 12);
			t.AddSelfInfo();
			t = Theater.GetTheaterByID(t.ID);
			if (t == null)
				System.Console.WriteLine("AddSelfInfo Wrong!");
			t.DeleteSelfInfo();
			t = Theater.GetTheaterByID(1);
			if (t == null)
				System.Console.WriteLine("GetTheaterByID Wrong!");
			t = Theater.GetTheaterByName("DSF");
			if (t == null)
				System.Console.WriteLine("GetTheaterByName Wrong!");
			Theater.DeleteItemFromDatabase(t.ID);
			t = Theater.GetTheaterByID(t.ID);
			if (t != null)
				System.Console.WriteLine("DeleteItemFromDatabase Wrong!");
			Theater.AddTheaterInfo(-1, "DSF", "ASDFASFasdf", "123afsd15", "5465adf43.com", 5.0M, "ASasdfDF", 12);
			t = Theater.GetTheaterByName("DSF");
			t.GetGrade(10);

			d = Theater.GetTheaterByName("DSF");
			if (d != null)
				d.DeleteSelfInfo();
			d = Theater.GetTheaterByName("DSF1asdf212");
			if (d != null)
				d.DeleteSelfInfo();
		}
		/// <summary>
		/// 获得当前最大的ID号
		/// </summary>
		/// <returns></returns>


	}
}